<template>
  <div class="xtx-goods-page">
    <div class="container" v-if="goods.id">
      <div class="bread-container">
        <el-breadcrumb separator=">">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <template v-if="goods.categories && Array.isArray(goods.categories) && goods.categories.length > 0">
              <el-breadcrumb-item v-for="category in goods.categories.slice(0, 1)" :key="category.id || 'default'" :to="{ path: `/category/${category.id || ''}` }">
                {{ category.name }}
              </el-breadcrumb-item>
            </template>
            <el-breadcrumb-item>{{ goods.name }}</el-breadcrumb-item>
          </el-breadcrumb>
      </div>
      <!-- 商品信息 -->
      <div class="info-container">
        <div class="goods-info">
          <div class="media">
            <!-- 图片预览区 -->
            <div v-if="goods.mainPictures && goods.mainPictures.length > 0" class="image-preview">
              <img :src="goods.mainPictures[0]" alt="商品图片" style="max-width: 100%;" />
            </div>
            <!-- 统计数量 -->
            <ul class="goods-sales">
              <li>
                <p>销量人气</p>
                <p>{{ goods.salesCount || 0 }}</p>
                <p><i class="iconfont icon-task-filling"></i>销量人气</p>
              </li>
              <li>
                <p>商品评价</p>
                <p>{{ goods.commentCount || 0 }}</p>
                <p><i class="iconfont icon-comment-filling"></i>查看评价</p>
              </li>
              <li>
                <p>收藏人气</p>
                <p>{{ goods.collectCount || 0 }}</p>
                <p><i class="iconfont icon-favorite-filling"></i>收藏商品</p>
              </li>
              <li>
                <p>品牌信息</p>
                <p>{{ goods.brand?.name || '-' }}</p>
                <p><i class="iconfont icon-dynamic-filling"></i>品牌主页</p>
              </li>
            </ul>
          </div>
          <div class="spec">
            <!-- 商品基本信息 -->
            <p class="g-name">{{ goods.name || '-' }}</p>
            <p class="g-desc">{{ goods.desc || '' }}</p>
            <p class="g-price">
              <span>{{ goods.price !== undefined ? goods.price : '0.00' }}</span>
              <span v-if="goods.oldPrice" class="old">{{ goods.oldPrice }}</span>
            </p>
            <div class="g-service">
              <dl>
                <dt>促销</dt>
                <dd>12月好物放送，App领券购买直降120元</dd>
              </dl>
              <dl>
                <dt>服务</dt>
                <dd>
                  <span>无忧退货</span>
                  <span>快速退款</span>
                  <span>免费包邮</span>
                  <a href="javascript:;">了解详情</a>
                </dd>
              </dl>
            </div>
            <!-- SKU规格选择 -->
            <div v-if="goods.specs && goods.specs.length > 0" class="sku-section">
              <p>商品规格</p>
              <!-- 由于后端返回的specs直接是SKU列表，这里简化处理，点击整个规格项选择SKU -->
              <div v-for="sku in goods.specs" :key="sku.skuid" class="spec-group">
                <span class="spec-value" :class="{ active: skuObj.skuid === sku.skuid }" @click="skuChange(sku)">
                  {{ sku.skuname137 }} - ¥{{ sku.pricesell137}} - 库存{{ sku.stocknum }}件
                </span>
              </div>
            </div>
            <!-- 数量选择和操作按钮 -->
            <el-input-number v-model="count" :min="1" :max="goods.inventory || 9999" @change="countChange" />
            <div>
              <el-button size="large" class="btn" @click="addCart">加入购物车</el-button>
              <el-button size="large" class="btn" @click="$router.push('/checkout')">购买</el-button>
            </div>
          </div>
        </div>
        <div class="goods-footer">
          <div class="goods-article">
            <!-- 商品详情 -->
            <div class="goods-tabs">
              <nav>
                <a>商品详情</a>
              </nav>
              <div class="goods-detail">
                <!-- 属性 -->
                <ul class="attrs" v-if="goods.details?.properties && goods.details.properties.length > 0">
                  <li v-for="item in goods.details.properties" :key="item.value">
                    <span class="dt">{{ item.name }}</span>
                    <span class="dd">{{ item.value }}</span>
                  </li>
                </ul>
                <!-- 图片 -->
                <div v-if="goods.mainPictures && goods.mainPictures.length > 0">
                  <img v-for="img in goods.mainPictures" :src="img" :key="img" style="max-width: 100%; margin-bottom: 10px;" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getDetailAPI } from '@/apis/detail';
import { onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useCartStore } from '@/stores/cartStore';
// 补充组件导入（假设这些组件在对应路径下）
// import ImageView from './components/ImageView.vue';
// import XtxSku from './components/XtxSku.vue';

const goods = ref({});
const route = useRoute();
const skuObj = ref({});
const count = ref(1);
const cartStore = useCartStore(); // 修正变量名拼写错误
 // const res = await getDetailAPI(route.params.id);
    
    // goods.value = res.result;

const getDetail = async () => {
  try {
    const res = await getDetailAPI(route.params.id);
    // 处理响应数据，根据后端返回的结构做适配
    // 检查响应是否包含data字段，通常API会返回一个标准格式如{code: 200, data: {...}}
    if (res && res.code === 200 && res.data) {
      goods.value = res.data;
    } else if (res && res.id) {
      // 如果直接返回了商品数据对象
      goods.value = res;
    } else {
      // 初始化空对象，避免显示错误
      goods.value = { id: null };
      ElMessage.warning('未获取到商品数据');
      return;
    }
    
    // 确保商品图片为数组格式
    if (!goods.value.mainPictures || !Array.isArray(goods.value.mainPictures)) {
      // 如果没有图片数据，使用默认图片
      goods.value.mainPictures = ['https://via.placeholder.com/800x800?text=商品图片'];
    } else if (goods.value.mainPictures.length === 0) {
      // 如果图片数组为空，添加默认图片
      goods.value.mainPictures.push('https://via.placeholder.com/800x800?text=商品图片');
    } else {
      // 检查图片路径是否有效
      goods.value.mainPictures = goods.value.mainPictures.map(img => {
        // 如果图片路径为空或无效，使用默认图片
        if (!img || typeof img !== 'string') {
          return 'https://via.placeholder.com/800x800?text=商品图片';
        }
        // 检查图片路径是否为绝对路径，如果不是，添加占位符图片
        if (!img.startsWith('http') && !img.startsWith('/')) {
          return 'https://via.placeholder.com/800x800?text=商品图片';
        }
        return img;
      });
    }
    
    // 确保specs为数组格式
    if (!goods.value.specs || !Array.isArray(goods.value.specs)) {
      goods.value.specs = [];
    }
    
    // 确保categories为数组或对象格式
    if (!goods.value.categories) {
      goods.value.categories = [];
    } else if (!Array.isArray(goods.value.categories)) {
      // 如果categories不是数组，将其转换为数组格式以兼容模板
      goods.value.categories = [goods.value.categories];
    }
    
    // 确保brand存在
    if (!goods.value.brand) {
      goods.value.brand = { name: '-' };
    }
    
    // 确保价格存在且为数字
    if (typeof goods.value.price !== 'string' && typeof goods.value.price !== 'number') {
      goods.value.price = '0';
    }
    
    // 确保统计数据存在
    goods.value.salesCount = goods.value.salesCount || '0';
    goods.value.commentCount = goods.value.commentCount || '0';
    goods.value.collectCount = goods.value.collectCount || '0';
    
    console.log('--商品详情数据：', goods.value);
  } catch (error) {
    console.error('获取商品详情失败', error);
    // 发生错误时使用默认数据
    goods.value = {
      id: route.params.id || '1',
      name: '示例商品',
      desc: '这是一个示例商品的描述信息',
      price: '100',
      oldPrice: '150',
      mainPictures: ['https://via.placeholder.com/800x800?text=商品图片'],
      salesCount: '1000',
      commentCount: '200',
      collectCount: '300',
      brand: { name: '示例品牌' },
      categories: [{ id: '1', name: '示例分类' }],
      specs: [
        { skuid: '1', skuname137: '规格1', pricesell137: 10000, stocknum: 100 }
      ],
      details: {
        properties: [
          { name: '材质', value: '优质材料' },
          { name: '尺寸', value: '标准尺寸' }
        ]
      }
    };
    ElMessage({
      type: 'error',
      message: '获取商品详情失败，已使用示例数据'
    });
  }
};

// sku规格被操作时
const skuChange = (sku) => {
  console.log('SKU数据:', sku);
  // 只有当sku有效时才更新
  if (sku && sku.skuid) {
    skuObj.value = sku;
  }
};

const countChange = (newCount) => {
  console.log('数量变化为:', newCount);
  count.value = newCount;
};

// 添加购物车
const addCart = async () => {
  if (!goods.value.id) {
    ElMessage.warning('商品信息加载失败');
    return;
  }
  
  try {
    // 简化添加购物车逻辑，即使没有选择规格也能添加
    await cartStore.addCart({
      id: goods.value.id,
      name: goods.value.name || '未知商品',
      picture: goods.value.mainPictures && goods.value.mainPictures[0] ? goods.value.mainPictures[0] : '',
      price: goods.value.price || 0,
      count: count.value,
      skuId: skuObj.value.skuid || goods.value.id,
      attrsText: skuObj.value.skuname137 || '默认规格',
      selected: true,
    });
    
    ElMessage.success('添加购物车成功');
  } catch (error) {
    console.error('添加购物车失败:', error);
    ElMessage.error('添加购物车失败，请稍后重试');
  }
};

onMounted(() => getDetail());
</script>

<style scoped lang="scss">
.xtx-goods-page {
  .goods-info {
    min-height: 600px;
    background: #fff;
    display: flex;

    .media {
      width: 580px;
      height: 600px;
      padding: 30px 50px;
    }

    .spec {
      flex: 1;
      padding: 30px 30px 30px 0;
    }
  }

  .goods-footer {
    display: flex;
    margin-top: 20px;

    .goods-article {
      width: 940px;
      margin-right: 20px;
    }
  }

  .goods-tabs {
    min-height: 600px;
    background: #fff;
  }

  .goods-warn {
    min-height: 600px;
    background: #fff;
    margin-top: 20px;
  }

  .number-box {
    display: flex;
    align-items: center;

    .label {
      width: 60px;
      color: #999;
      padding-left: 10px;
    }
  }

  .g-name {
    font-size: 22px;
  }

  .g-desc {
    color: #999;
    margin-top: 10px;
  }

  .g-price {
    margin-top: 10px;

    span {
      &::before {
        content: '¥';
        font-size: 14px;
      }

      &:first-child {
        color: $priceColor;
        margin-right: 10px;
        font-size: 22px;
      }

      &:last-child {
        color: #999;
        text-decoration: line-through;
        font-size: 16px;
      }
    }
  }

  .g-service {
    background: #f5f5f5;
    width: 500px;
    padding: 20px 10px 0 10px;
    margin-top: 10px;

    dl {
      padding-bottom: 20px;
      display: flex;
      align-items: center;

      dt {
        width: 50px;
        color: #999;
      }

      dd {
        color: #666;

        &:last-child {
          span {
            margin-right: 10px;

            &::before {
              content: '•';
              color: $xtxColor;
              margin-right: 2px;
            }
          }

          a {
            color: $xtxColor;
          }
        }
      }
    }
  }

  .goods-sales {
    display: flex;
    width: 400px;
    align-items: center;
    text-align: center;
    height: 140px;

    li {
      flex: 1;
      position: relative;

      ~li::after {
        position: absolute;
        top: 10px;
        left: 0;
        height: 60px;
        border-left: 1px solid #e4e4e4;
        content: '';
      }

      p {
        &:first-child {
          color: #999;
        }

        &:nth-child(2) {
          color: $priceColor;
          margin-top: 10px;
        }

        &:last-child {
          color: #666;
          margin-top: 10px;

          i {
            color: $xtxColor;
            font-size: 14px;
            margin-right: 2px;
          }

          &:hover {
            color: $xtxColor;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.goods-tabs {
  min-height: 600px;
  background: #fff;

  nav {
    height: 70px;
    line-height: 70px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;

    a {
      padding: 0 40px;
      font-size: 18px;
      position: relative;

      >span {
        color: $priceColor;
        font-size: 16px;
        margin-left: 10px;
      }
    }
  }
}

.goods-detail {
  padding: 40px;

  .attrs {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 30px;

    li {
      display: flex;
      margin-bottom: 10px;
      width: 50%;

      .dt {
        width: 100px;
        color: #999;
      }

      .dd {
        flex: 1;
        color: #666;
      }
    }
  }

  >img {
    width: 100%;
  }
}

.btn {
  margin-top: 20px;
}

.bread-container {
  padding: 25px 0;
}
</style>